import router from './index'
import store from '@/store'
import api from '@/api'
import { handleTree } from '@/utils'

// 路径类型映射
const typePath = {
  '1': '/about', // 栏目
  '2': '/product', // 产品
  '3': '/case', // 案例
  '4': '/news' // 新闻动态
}

// 从路径中提取导航ID
const getNavIdFromPath = (path) => {
  if (!path || path === '/') return null
  
  const match = path.match(/^\/[^/]+\/(\d+)/)
  return match && match[1] ? parseInt(match[1]) : null
}

// 加载导航数据
export const loadNavData = async () => {
  try {
    const res = await api.getCategoryList()
    if (!res || !res.data) return false
    
    // 处理导航数据
    const list = res.data.map(item => {
      const basePath = typePath[item.type]
      if (item.parentId === 0) {
        item.path = `${basePath}/${item.id}`
      }
      return item
    })
    
    // 保存原始导航数据
    store.dispatch('setBaseNav', list)
    
    // 将扁平结构转换为树形结构
    const treeData = handleTree(list)
    store.dispatch('setNavList', treeData)
    
    return true
  } catch (error) {
    console.error('加载导航数据失败:', error)
    return false
  }
}

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  document.title = '环泽科技'
  // 确保导航数据已加载
  if (store.getters.navList.length === 0) {
    await loadNavData()
  }
  
  const path = to.path

  if (from.path.includes('detail')) {
    localStorage.removeItem('navInfo')
  }
  
  // 提取导航ID
  const navId = getNavIdFromPath(path)
  
  // 找到对应的导航项
  if (navId) {
    const baseNav = store.getters.baseNav
    const navItem = baseNav.find(item => item.id === navId)
    
    if (navItem) {
      next()
      return
    }
  }
  
  // 直接放行
  next()
})

// 路由后置守卫
router.afterEach(() => {
  
})
